import {Component, Input, OnInit} from '@angular/core';
import {StringUtil} from '../../../util/StringUtil';
import {GlobalService} from '../../../service/GlobalService';
import {NzModalRef} from 'ng-zorro-antd';
import {Constant} from '../../../util/Constant';
import {ModelRes} from '../../../entity/ModelRes';

@Component({
  selector: 'app-forget-psw',
  templateUrl: './forget-psw.component.html',
  styleUrls: ['./forget-psw.component.less']
})
export class ForgetPswComponent implements OnInit {

  @Input()
  phone: string;

  sendCodeStr = StringUtil.CODE_SEND;
  cantSend = false;
  sendWaitTime = 0;

  psw;
  code;

  constructor(public app: GlobalService, private modal: NzModalRef) {
  }

  ngOnInit() {
  }

  sendCode() {
    if (this.cantSend) {
      return;
    }
    if (this.phone === '') {
      this.app.err('请输入手机号');
      return;
    }
    this.app.req(Constant.SEND_RESET_PSW, {'phone': this.phone}).then((json: ModelRes) => {
      this.waitSend();
    });
  }

  setPsw() {

    if (this.phone === '') {
      this.app.err('请输入手机号');
      return;
    }
    if (this.code === '') {
      this.app.err('请输入验证码');
      return;
    }
    if (this.psw === '') {
      this.app.err('请输入密码');
      return;
    }

    this.app.req(Constant.RESET_PSW, {'phone': this.phone, 'psw': this.psw, 'code': this.code}).then(json => {
      this.modal.destroy();
    });
  }

  waitSend() {
    this.cantSend = true;
    this.sendWaitTime = 60;
    const interval = setInterval(() => {
      if (this.sendWaitTime <= 0) {
        this.cantSend = false;
        this.sendCodeStr = StringUtil.CODE_SEND;
        clearInterval(interval);
      } else {
        this.sendCodeStr = this.sendWaitTime + StringUtil.CODE_WAIT;
      }
      this.sendWaitTime--;
    }, 1000);
  }

}
